<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false" effect="dark">
      </el-alert>
      <!-- 级联选择器 -->
      <el-row style="margin:20px 0">
        <el-col :span="24">
          <span>选择商品分类：</span>
          <el-cascader v-model="pCateKeys" :options="pCateList"
            :props="{ expandTrigger: 'hover' ,label:'cat_name',value:'cat_id'}" @change="pIdChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tabs -->
      <el-tabs v-model="activeName" type="border-card" @tab-click="cateHandleClick">
        <!-- 动态 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="pCateKeys.length!==3" @click="addDialogVisible=true">添加参数
          </el-button>
          <!-- 动态表格 -->
          <el-table :data="manyList" stripe border style="width: 100%">
            <el-table-column type="expand" label="展开">
              <template slot-scope="{row}">
                <el-tag :key="index" v-for="(item,index) in row.attr_vals" closable :disable-transitions="false"
                  @close="tagRemove(row,index)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model.trim="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{row}">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(row)">修改
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="remove(row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="pCateKeys.length!==3" @click="addDialogVisible=true">添加属性
          </el-button>
          <!-- 静态表格 -->
          <el-table :data="onlyList" stripe border style="width: 100%">
            <el-table-column type="expand" label="展开">
              <template slot-scope="{row}">
                <el-tag :key="index" v-for="(item,index) in row.attr_vals" closable :disable-transitions="false"
                  @close="tagRemove(row,index)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="row.inputVisible" v-model.trim="row.inputValue" ref="saveTagInput"
                  size="small" @keyup.enter.native="handleInputConfirm(row)" @blur="handleInputConfirm(row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#">
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{row}">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(row)">修改
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="remove(row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="addDialogVisible" @close="resetaddForm" width="50%">
      <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveParams">确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 编辑参数对话框 -->
    <el-dialog :title="'添加'+titleText" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules="addRules" ref="editForm" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 级联选择的分类
      pCateKeys: [1, 3, 6],
      // 商品分类列表
      pCateList: [],
      // tab当前页
      activeName: 'many',
      // 商品动态参数
      manyList: [],
      // 静态属性
      onlyList: [],
      // 添加参数对话框 显隐
      addDialogVisible: false,
      // 添加参数对话框 表单数据
      addForm: {
        attr_name: ''
      },
      // 规则
      addRules: {
        attr_name: [
          { required: true, message: '参数名称不能为空', trigger: 'blur' }
        ]
      },
      // 编辑参数对话框 显隐
      editDialogVisible: false,
      // 编辑参数对话框 表单数据
      editForm: {
        attr_id: '',
        attr_name: ''
      },
      // tag
      inputVisible: false

    }
  },
  created () {
    this.addCate()
    this.getParamsDate()
  },
  methods: {
    // 添加分类对话框显示
    async addCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      // console.log(res)
      this.pCateList = res.data
      this.addcateDialogVisible = true
    },
    // 获取商品参数数据
    async getParamsDate () {
      const { data: res1 } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
      console.log(res1)
      if (res1.meta.status !== 200) return this.$message.error('获取商品参数失败')
      res1.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputValue = ''
        item.inputVisible = false
      })
      this.manyList = res1.data
      const { data: res2 } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
      console.log(res2)
      if (res2.meta.status !== 200) return this.$message.error('获取商品参数失败')
      res2.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputValue = ''
        item.inputVisible = false
      })
      this.onlyList = res2.data
    },
    // 监听级联值改变
    pIdChange () {
      if (this.pCateKeys.length !== 3) {
        this.pCateKeys = []
        // this.pCateList = []
        this.manyList = []
        this.onlyList = []
        return this.$message.warning('只允许为三级分类设置参数!')
      }
      this.getParamsDate()
    },
    // 切换tab事件
    cateHandleClick () {
      // console.log(this.activeName)
    },
    // 添加对话框 参数提交 确认按钮点击事件
    saveParams () {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return this.$message.warning('请填写参数名')
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addForm.attr_name, attr_sel: this.activeName })
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加商品参数失败')
        this.$message.success('添加商品参数成功')
        this.getParamsDate()
        this.addDialogVisible = false
      })
    },
    // 对话框关闭
    resetaddForm () {
      this.$refs.addForm.resetFields()
    },
    // 编辑对话框弹出
    showEditDialog (row) {
      this.editDialogVisible = true

      this.editForm = { ...row }
    },
    // 编辑对话框 参数提交 确认按钮点击事件
    editParams () {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) return this.$message.warning('请填写参数名')
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, { attr_name: this.editForm.attr_name, attr_sel: this.activeName, attr_vals: this.editForm.attr_vals.join(' ') })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('修改商品参数失败')
        this.$message.success('修改商品参数成功')
        this.getParamsDate()
        this.editDialogVisible = false
      })
    },
    // 删除
    remove (row) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${row.attr_id}`)
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParamsDate()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 点击tag自动获得焦点
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加参数 属性
    async handleInputConfirm (row) {
      if (row.inputValue === '') {
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.$message.success('更新成功')
      row.inputValue = ''
      row.inputVisible = false
    },
    // 删除tag
    async tagRemove (row, i) {
      row.attr_vals.splice(i, 1)
      const { data: res } = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: this.activeName, attr_vals: row.attr_vals.join(' ') })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
    }
  },
  computed: {
    // 获取级联绑定的分类id
    cateId () {
      if (this.pCateKeys.length === 3) {
        return this.pCateKeys[2]
      } else {
        return null
      }
    },
    // 获取对话框标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }
  }

}
</script>

<style scoped lang='less'>
.el-tag {
  margin: 5px;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
